package com.ks.utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 
 * Cookie 工具类
 *
 */
public final class CookieUtils {
	private CookieUtils() {
		throw new UnsupportedOperationException();
	}

	private static final Logger log = LoggerFactory.getLogger(CookieUtils.class);

	/**
	 * @Description 立即删除所有Cookie
	 * @param request
	 * @param response
	 */
	public static void deleteCookieNow(HttpServletRequest request, HttpServletResponse response, String... cookieName) {
		Cookie[] cookie = request.getCookies();
		if (cookieName.length == 0) {
			for (Cookie c : cookie) {
				c.setMaxAge(0);
				response.addCookie(c);
			}
		} else {
			for (int i = 0; i < cookieName.length; i++) {
				for (Cookie c : cookie) {
					if (cookieName[i].equals(c.getName())) {
						c.setMaxAge(0);
						response.addCookie(c);
					}
				}
			}

		}

	}

	/**
	 * @Description 关闭浏览器时删除所有Cookie
	 * @param request
	 * @param response
	 */
	public static void deleteCookie(HttpServletRequest request, HttpServletResponse response) {
		Cookie[] cookie = request.getCookies();
		for (Cookie c : cookie) {
			c.setMaxAge(-1);
			response.addCookie(c);
		}
	}

//	/**
//	 * 将cookie封装到Map里面
//	 * 
//	 * @param request
//	 * @return
//	 */
//	public static Map<String, Cookie> readCookieMap(HttpServletRequest request) {
//		Map<String, Cookie> cookieMap = new HashMap<>();
//		Cookie[] cookies = request.getCookies();
//		if (null != cookies) {
//			for (Cookie cookie : cookies) {
//				cookieMap.put(cookie.getName(), cookie);
//			}
//		}
//		return cookieMap;
//	}
//

	/**
	 * 得到Cookie的值,选择是否UTF-8编码
	 * 
	 * @param request
	 * @param cookieName
	 * @param isDecoder  是否进行UTF-8编码
	 * @return
	 */
	public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
		Cookie[] cookieList = request.getCookies();
		if (cookieList == null || cookieName == null) {
			return "";
		}
		String retValue = "";
		try {
			for (int i = 0; i < cookieList.length; i++) {
				if (cookieList[i].getName().equals(cookieName)) {
					if (isDecoder) {
						retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
					} else {
						retValue = cookieList[i].getValue();
					}
					break;
				}
			}
		} catch (UnsupportedEncodingException e) {
			log.error("编码错误！", e);
		}
		return retValue;
	}

	/**
	 * 删除指定Cookie,立即生效
	 */
	public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
		doSetCookie(request, response, cookieName, "", 0, null, "/");
	}

	/**
	 * @Description 添加cookie
	 * @param request
	 * @param response
	 * @param cookieName
	 * @param cookieValue
	 * @param cookieMaxage -1浏览器关闭失效，0立即失效，大于0为失效时间
	 * @param isEncode     是否UTF-8编码
	 */
	public static void addCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
			String cookieValue, int cookieMaxage, boolean isEncode) {
		if (isEncode) {
			doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, "UTF-8", "/");
		} else {
			doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, null, "/");

		}
	}

	private static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName,
			String cookieValue, int cookieMaxage, String encodeString, String savePath) {
		try {
			if (cookieValue == null) {
				cookieValue = "";
			}
			if (encodeString != null) {
				cookieValue = URLEncoder.encode(cookieValue, encodeString);
			}
			Cookie cookie = new Cookie(cookieName, cookieValue);
			cookie.setMaxAge(cookieMaxage);
			if (null != request) {
				// 设置域名的cookie
//				String domainName = getDomainName(request);
				String domainName = request.getServerName();
				log.debug("域名【{}】", domainName);
				//上线时测试
				if (!"localhost".equals(domainName)) {
					cookie.setDomain(domainName);
				}
			}
			//设置浏览器客户端js不能读取cookie一定程度减少xss攻击
//			cookie.setHttpOnly(true);
			cookie.setPath(savePath);
			response.addCookie(cookie);
		} catch (Exception e) {
			log.error("设置Cookie错误", e);
		}
	}

	/**
	 * 得到cookie的域名
	 */

//	private static final String getDomainName(HttpServletRequest request) {
//		String domainName = null;
//		String serverName = request.getRequestURL().toString();
//		if (serverName == null || serverName.equals("")) {
//			domainName = "";
//		} else {
//			final int end = serverName.lastIndexOf('/');
//			serverName = serverName.substring(0, end);
//			final String[] domains = serverName.split("\\.");
//			int len = domains.length;
//			if (len > 3) {
//				// www.xxx.com.cn
//				domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
//			} else if (len <= 3 && len > 1) {
//				// xxx.com or xxx.cn
//				domainName = "." + domains[len - 2] + "." + domains[len - 1];
//			} else {
//				domainName = serverName;
//			}
//		}
//
//		if (domainName != null && domainName.indexOf(":") > 0) {
//			String[] ary = domainName.split("\\:");
//			domainName = ary[0];
//		}
//		return domainName;
//	}

}
